<template>
    <div class="login-dialog">
        <el-dialog
            v-model="state.show"
            center
            draggable
            :before-close="onClose"
        >
            <div class="login-box">
                <div class="login-light-show">
                    <img src="~/assets/web/images/login_image.jpg" :alt="siteConfig.siteName">
                </div>
                <div v-if="state.type == 'login'" class="login-account-box">
                    <div class="login-form">
                        <el-tabs v-model="state.tab_login" @tab-click="handleClick">
                            <el-tab-pane label="账号密码登录" name="account">
                                <el-form :model="state.form">
                                    <el-form-item size="large">
                                        <el-input v-model="state.form.username" placeholder="输入你的邮箱/手机号" prop="count" prefix-icon="el-icon-User" />
                                    </el-form-item>
                                    <el-form-item size="large">
                                        <el-input v-model="state.form.password" placeholder="输入你的密码" type="password" show-password prefix-icon="el-icon-Lock" />
                                    </el-form-item>
                                    <el-form-item class="login-form-remember">
                                        <el-checkbox>记住我</el-checkbox>
                                        <el-link type="info">忘记密码？</el-link>
                                    </el-form-item>
                                    <el-form-item size="large" class="login-form-button">
                                        <el-button type="primary" @click="clickLogin">立即登录</el-button>
                                    </el-form-item>
                                    <el-form-item class="login-form-remember1">
                                        <span>没有账号？<el-link type="primary" @click="click_tab('register')">立即注册</el-link></span>
                                    </el-form-item>
                                </el-form>
                            </el-tab-pane>
                            <el-tab-pane v-if="siteConfig.user_login_phone == 1" label="手机验证登录" name="phone">
                                <el-form :model="state.form">
                                    <el-form-item size="large">
                                        <el-input v-model="state.form.mobile" placeholder="输入你的手机号" prop="count" prefix-icon="el-icon-Iphone">
                                            <template #prepend>
                                                <el-select v-model="state.form.country" style="width: 80px">
                                                    <el-option label="+86" value="+86"></el-option>
                                                </el-select>
                                            </template>
                                        </el-input>
                                    </el-form-item>
                                    <el-form-item size="large">
                                        <el-row :gutter="10">
                                            <el-col :span="16">
                                                <el-input v-model="state.form.captcha" placeholder="请填写您的验证码" type="number" prefix-icon="el-icon-Document" />
                                            </el-col>
                                            <el-col :span="8">
                                                <el-button
                                                    type="primary"
                                                    @click="sendLogonCaptchaPre"
                                                    :loading="state.sendCaptchaLoading"
                                                    :disabled="state.codeSendCountdown <= 0 ? false : true"
                                                >
                                                    {{ state.codeSendCountdown <= 0 ? '获取验证码' : state.codeSendCountdown + '秒' }}
                                                </el-button>
                                            </el-col>
                                        </el-row>
                                    </el-form-item>
                                    <el-form-item size="large" class="login-form-button">
                                        <el-button type="primary" @click="click_mobile_Login">手机登录</el-button>
                                    </el-form-item>
                                </el-form>
                            </el-tab-pane>
                            <el-tab-pane v-if="siteConfig.user_login_wechat == 1" label="微信登录" name="wechat">
                                <div class="login-form-wechat">
                                    <el-image>
                                        <template #error>
                                            <div class="image-slot" v-loading="state.loading">
                                                <span @click="onRefresh">点击刷新</span>
                                            </div>
                                        </template>
                                    </el-image>
                                    <span class="login-form-wechat-text">微信扫码登录/注册</span>
                                    <span class="login-form-wechat-text1">首次扫码关注公众号后将自动注册新账号</span>
                                </div>
                            </el-tab-pane>
                        </el-tabs>
                    </div>
                    <div class="login-form-footer">
                        <div class="login-form-footer-item">
                            <span>您登录即同意<el-link class="">用户协议</el-link>和<el-link>隐私政策</el-link></span>
                        </div>
                    </div>
                </div>
                <div v-if="state.type == 'register'" class="login-account-box">
                    <div class="login-form">
                        <el-tabs v-model="state.tab_register" @tab-click="handleClick">
                            <el-tab-pane label="账号注册" name="account">
                                <el-form :model="state.form">
                                    <el-form-item size="large">
                                        <el-input v-model="state.form.username" placeholder="请输入用户名" prop="count" prefix-icon="el-icon-User" />
                                    </el-form-item>
                                    <el-form-item size="large">
                                        <el-input v-model="state.form.password" placeholder="请输入密码" type="password" show-password prefix-icon="el-icon-Lock" />
                                    </el-form-item>

                                    <el-form-item v-if="siteConfig.user_register_verify == 'email'" size="large">
                                        <el-input v-model="state.form.email" placeholder="请填写您的邮箱" type="email" prefix-icon="el-icon-Message" />
                                    </el-form-item>
                                    <el-form-item v-if="siteConfig.user_register_verify == 'mobile'" size="large">
                                        <el-input v-model="state.form.mobile" placeholder="请填写您的手机号" type="number" prefix-icon="el-icon-Iphone" />
                                    </el-form-item>

                                    <el-form-item v-if="siteConfig.user_register_verify !== '0'" size="large">
                                        <el-row :gutter="10">
                                            <el-col :span="16">
                                                <el-input v-model="state.form.captcha" placeholder="请填写您的验证码" prefix-icon="el-icon-Document" />
                                            </el-col>
                                            <el-col :span="8">
                                                <el-button
                                                    type="primary"
                                                    @click="sendRegisterCaptchaPre"
                                                    :loading="state.sendCaptchaLoading"
                                                    :disabled="state.codeSendCountdown <= 0 ? false : true"
                                                >
                                                    {{ state.codeSendCountdown <= 0 ? '获取验证码' : state.codeSendCountdown + '秒' }}
                                                </el-button>
                                            </el-col>
                                        </el-row>
                                    </el-form-item>

                                    <el-form-item size="large">
                                        <el-input v-model="state.form.invite_code" placeholder="填写您的邀请码（可选）" prefix-icon="el-icon-PriceTag" />
                                    </el-form-item>

                                    <el-form-item size="large" class="login-form-button">
                                        <el-button type="primary" @click="clickLogin">立即注册</el-button>
                                    </el-form-item>
                                    <el-form-item class="login-form-remember1">
                                        <span>已有账号？<el-link type="primary" @click="click_tab('login')">立即登录</el-link></span>
                                    </el-form-item>
                                </el-form>
                            </el-tab-pane>
                        </el-tabs>
                    </div>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import {reactive, watch} from "vue"
import {ElNotification, TabsPaneContext} from 'element-plus'
import {uuid} from "/@/utils/random";
import {login, register, mobileLogin} from "/@/api/frontend/user/index"
import { useUserInfo } from "/@/stores/userInfo";
import {sendEms, sendSms} from "/@/api/common";
import { useSiteConfig } from '/@/stores/siteConfig'
import {useRouter} from "vue-router";
import clickCaptcha from '/@/components/clickCaptcha'

const props = defineProps({
    visible: {
        type: Boolean,
        default: false
    }
})

const siteConfig = useSiteConfig()
const router = useRouter()
const userInfo = useUserInfo()

const state = reactive({
    loading: false,
    show: props.visible,
    type: 'login',
    tab_login: 'account',
    tab_register: 'account',
    data: {
        title: '登录',
    },
    form: {
        username: '',
        password: '',
        email: '',
        country: '+86',
        mobile: '',
        invite_code: '',
        registerType: 'email',
        loginType: 'mobile',
        captchaId: uuid(),
        captcha: ''
    },
    codeSendCountdown: 0,
    sendCaptchaLoading: false,
    registerType: 'email',
    loginType: 'mobile',
})

const handleClick = (tab: TabsPaneContext, event: Event) => {
    // state.registerType = tab.props.name
    // console.log(state.registerType)
}

const onClose = () => {
    state.show = false
}

// 监听props.visible
watch(() => props.visible, (val) => {
    state.show = true
})

const onRefresh = () => {
    state.loading = true
    setTimeout(() => {
        state.loading = false
    }, 2000)
}

const click_tab = (tabName: string) => {
    state.type = tabName
    if (tabName === 'login') {
        state.data.title = '登录'
    } else {
        state.data.title = '注册'
    }
}

// 手机登录
const click_mobile_Login = () => {
    if (state.form.mobile === '') {
        ElNotification({
            message: '请输入你的手机号',
            type: 'warning'
        })
        return false
    }
    if (state.form.captcha === '') {
        ElNotification({
            message: '请输入你的验证码',
            type: 'warning'
        })
        return false
    }
    state.loading = true
    // 请求登录数据
    mobileLogin({
        mobile: state.form.mobile,
        captcha: state.form.captcha,
    }).then((res) => {
        if (res.code === 1) {
            state.loading = false
            userInfo.dataFill(res.data.userInfo)
            state.show = false
            router.go(0)
        }
    })
}

const clickLogin = () => {
    if (state.form.username === '') {
        ElNotification({
            message: '请输入你的用户名',
            type: 'warning'
        })
        return false
    }
    if (state.form.password === '') {
        ElNotification({
            message: '请输入你的密码',
            type: 'warning'
        })
        return false
    }
    // 验证用户名，需要字母开头
    if(state.form.username !== '') {

        // 如果登录username
        if(state.type === 'register') {
            const reg = /^[a-zA-Z][a-zA-Z0-9_]{4,15}$/
            if (!reg.test(state.form.username)) {
                ElNotification({
                    message: '用户名必须以字母开头，允许5-16字节，允许字母数字下划线',
                    type: 'warning'
                })
                return false
            }
        }
    }

    // 验证手机号
    const regMobile = /^1[3456789]\d{9}$/
    if (state.form.mobile !== '' && !regMobile.test(state.form.mobile)) {
        ElNotification({
            message: '请输入正确的手机号',
            type: 'warning'
        })
        return false
    }

    state.loading = true
    // 请求登录数据
    if (state.type === 'login') {
        login({
            username: state.form.username,
            password: state.form.password,
            keep: 1
        }).then((res) => {
            if (res.code === 1) {
                state.loading = false
                userInfo.dataFill(res.data.userInfo)
                state.show = false
                router.go(0)
            }
        })
    } else {
        state.form.registerType = siteConfig.user_register_verify
        register(state.form).then((res) => {
            if (res.code === 1) {
                state.loading = false
                userInfo.dataFill(res.data.userInfo)
                state.show = false
                router.go(0)
            }
        })
    }
}

// 发送验证码
let timer: number
const endTiming = () => {
    state.codeSendCountdown = 0
    clearInterval(timer)
}
const startTiming = (seconds: number) => {
    state.codeSendCountdown = seconds
    timer = window.setInterval(() => {
        state.codeSendCountdown--
        if (state.codeSendCountdown <= 0) {
            endTiming()
        }
    }, 1000)
}
// 登录验证码
const sendLogonCaptchaPre = () => {
    if (state.codeSendCountdown > 0) return
    if(state.loginType === 'mobile') {
        if (state.form.mobile === '') {
            ElNotification({
                message: '请输入你的手机号',
                type: 'warning'
            })
            return false
        }
    }
    clickCaptcha(state.form.captchaId, (captchaInfo: string) => sendLogonCaptcha(captchaInfo))
}

const sendLogonCaptcha = (captchaInfo: string) => {
    state.sendCaptchaLoading = true
    const func = state.form.loginType == 'email' ? sendEms : sendSms
    func(state.form[state.form.loginType], 'user_login', {
        captchaInfo,
        captchaId: state.form.captchaId,
    }).then((res) => {
        if (res.code == 1) startTiming(60)
    }).finally(() => {
        state.sendCaptchaLoading = false
    })
}

// 注册验证码
const sendRegisterCaptchaPre = () => {
    console.log(state.form)
    if (state.codeSendCountdown > 0) return
    state.registerType = siteConfig.user_register_verify
    if(state.registerType === 'email') {
        if (state.form.email === '') {
            ElNotification({
                message: '请输入你的邮箱',
                type: 'warning'
            })
            return false
        }
    } else {
        if (state.form.mobile === '') {
            ElNotification({
                message: '请输入你的手机号',
                type: 'warning'
            })
            return false
        }
    }
    clickCaptcha(state.form.captchaId, (captchaInfo: string) => sendRegisterCaptcha(captchaInfo))
}
const sendRegisterCaptcha = (captchaInfo: string) => {
    state.sendCaptchaLoading = true
    state.form.registerType = siteConfig.user_register_verify
    const func = state.form.registerType == 'email' ? sendEms : sendSms
    func(state.form[state.form.registerType], 'user_register', {
        captchaInfo,
        captchaId: state.form.captchaId,
    }).then((res) => {
        if (res.code == 1) startTiming(60)
    }).finally(() => {
        state.sendCaptchaLoading = false
    })
}
</script>

<style scoped lang="scss">
.login-dialog {
    :deep(.el-dialog) {
        width: 90%;
        max-width: 700px;
        border-radius: 14px;
        overflow: hidden;
        .el-dialog__header, .el-dialog__body {
            padding: 0;
        }
    }
    .login-box {
        display: flex;
        justify-content: space-between;
        .login-light-show {
            display: flex;
            justify-content: center;
            align-items: center;
            img {
                width: 320px;
                height: 100%;
                min-height: 420px;
                object-fit: cover;
            }
        }
        .login-account-box {
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            flex: 1;
            .login-form {
                flex: 1;
                padding: 30px 30px 0 30px;
                .login-form-wechat {
                    display: flex;
                    align-items: center;
                    flex-direction: column;
                    .el-image {
                        margin-top: 20px;
                        width: 180px;
                        height: 180px;
                        .image-slot {
                            display: flex;
                            justify-content: center;
                            align-items: center;
                            width: 100%;
                            height: 100%;
                            background-color: #666;
                            span {
                                color: #fff;
                                font-size: 14px;
                                cursor: pointer;
                            }
                        }
                    }
                    .login-form-wechat-text {
                        margin-top: 12px;
                    }
                    .login-form-wechat-text1 {
                        margin-top: 14px;
                        font-size: 12px;
                        color: #999;
                    }
                }
                .login-form-remember {
                    :deep(.el-form-item__content) {
                        display: flex;
                        justify-content: space-between;
                        align-items: center;
                    }
                }
                .login-form-remember1 {
                    :deep(.el-form-item__content) {
                        display: flex;
                        justify-content: center;
                        align-items: center;
                    }
                }
                .login-form-button {
                    :deep(.el-form-item__content) {
                        .el-button {
                            width: 100%;
                        }
                    }
                }
            }
            .login-form-footer {
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 15px 20px;
                background-color: #f4f4f4;
                margin-top: 12px;
                .login-form-footer-item {
                    span {
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        color: #999;
                        .el-link--default {
                            margin: 0 5px;
                        }
                    }
                }
            }
        }
    }
}
@media screen and (max-width: 768px) {
    .login-dialog {
        :deep(.el-dialog) {
            border-radius: 5px;
        }
        .login-box {
            .login-light-show {
                display: none;
            }
            .login-account-box {
                .login-form {
                    padding: 30px 20px 0 20px;
                }
            }
        }
    }
}
html {
    &.dark {
        .login-form-footer {
            background-color: var(--bg-color-pale) !important;
        }
    }
}
</style>
